let express = require("express")
let mysql = require("mysql");
let urll = require("url")
let form = require("formidable");
let connection = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "mm"
})
connection.connect();
let cookie = require("cookie-parser");
let app = express();
let session = require("express-session");
let server = require("http").Server(app);
let io = require("socket.io")(server);
app.use(cookie());
app.use(session({
  secret: "msx",
  resave: true,
  saveUninitialized: false
}))
app.use(express.static("node_modules"));
app.set("view engine", "ejs")
app.set("views", "./views")
app.get("/index", (req, res) => {
  res.render("index")
  res.end();
})

// 加载登录页
app.get("/login", (req, res) => {
  res.render("login");
  res.end();
})

app.get("/youke", (req, res) => {
  res.render("youke");
  res.end();
})

// 执行登陆的路由
app.post("/dologin", (req, res) => {
  // 接收表单传递的账号和密码
  let form2 = new form.IncomingForm();
  form2.parse(req, (err, fields) => {
    let { username, pass } = fields;
    // 把用户传递的用户名当成查询的条件 如果查询到 表示账号存在
    //   console.log(fields);
    let sql = "select * from users where username=?";
    let name = [username];
    let sql2 = mysql.format(sql, name);
    // res.end()
    connection.query(sql2, (err, results) => {
      console.log(results);
      if (results.length > 0) {
        // 进入这个分支表示账号没有问题
        // 需要判断密码
        if (pass == results[0].password) {
          console.log("登陆成功~");
          res.cookie("setcookiedata1", username);
          res.render("index", { data: results });
          // res.redirect('/index');
          res.end();
        }
      } else {
        // 进入这个分支表示账号有问题
        console.log("输入的账号或密码错误！");
        res.end();
      }
    })
  })
})

// 退出登录
app.get("/out", (req, res) => {
  res.clearCookie("setcookiedata1");
  res.redirect("/login");
  res.end()
})

// 历史记录
app.get("/his-bottom", (req, res) => {
  sql = "select * from history"
  connection.query(sql, (err, results) => {
    if (!err) {
      console.log(results);
      res.json({ "ls": results })
    } else {
      console.log("失败了")
    }
  })
})

server.listen(8090);

io.on("connection", socket => {
  socket.on("msx020703", res => {
    console.log(res);
    let { name, msg } = res
    let sql = "insert into history (name,msg) value (?,?)"
    let ins = [name, msg]
    let sql2 = mysql.format(sql, ins)
    connection.query(sql2, (err, results) => {
      if (!err) {
        if (results.affectedRows > 0) {
          console.log("插入成功")
        }
      } else {
        console.log("插入失败")
        console.log(err)
      }
    })
    socket.broadcast.emit("msx020703", res)
  })
  // 上线
  socket.on('up', res => {
    console.log(res);
    socket.broadcast.emit('up', res);
  })

  // 下线
  socket.on('outt', res => {
    console.log(res);
    socket.broadcast.emit('outt', res)
  })
})